﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Tools.Admin.Models;
using Newtonsoft.Json;
using System.IO;
using System.Text;

namespace Tools.Admin.Controllers
{
    public class HomeController : ToolsControllerBase
    {
        #region View
        // GET: Home
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult Main()
        {
            return View();
        }
        //demo 
        public ActionResult BTable()
        {
            return View();
        }
        //添加数据
        public ActionResult Create()
        {
            return View();
        }
        #endregion
        #region Handler
        //demo btable loadData
        public ActionResult GetDataPages()
        {
            var pageIndex = Request["pageIndex"];
            var pageSize = Request["pageSize"];
            var name = Request["name"];
            IList<Student> list = GetStudents();
            if (!string.IsNullOrEmpty(name))
                list = list.Where(p => p.Name.Contains(name)).ToList();
            return JsonResultForTable(true, "获取成功", list, 56);
        }
        //初始化数据
        public ActionResult InitData()
        {
            try
            {
                var init_data = Read(Server.MapPath("~/init_students.json"));
                Write(Server.MapPath("~/students.json"), init_data);
                return JsonResult(true, "初始化成功.");
            }
            catch (Exception ex)
            {
                return JsonResult(false, "初始化失败,错误信息：" + ex.Message);
            }
        }
        //处理新增表单
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(FormModel model)
        {
            return JsonResult(false, "提交失败" + model.Name);
        }
        //获取导航菜单
        public ActionResult GetNavs()
        {
            //读取数据
            var json = Read(Server.MapPath("~/nav.json"));
            //将数据序列化成一个对象，实际开发，这个对象是通过读取数据库获得的数据列表
            var navbars = JsonConvert.DeserializeObject<IList<Navbar>>(json);
            //除开nav.json文件提供的数据，额外添加的一个项
            navbars.Add(new Navbar
            {
                title = "这是额外添加的.",
                icon = "fa-user",
                href = "http://kit.zhengjinfan.cn/"
            });
            if (Request.HttpMethod.ToUpper() == "GET")
                return Json(navbars, JsonRequestBehavior.AllowGet);
            return Json(navbars);
        }
        //删除
        public ActionResult Delete(int id)
        {
            try
            {
                var students = GetStudents();
                students.Remove(students.FirstOrDefault(p => p.ID == id));
                WriteStudents(JsonConvert.SerializeObject(students));
                return JsonResult(true, "删除成功!");
            }
            catch (Exception ex)
            {
                return JsonResult(false, "删除成功,错误信息：" + ex.Message);
            }
        }
        #endregion
        #region Private
        //获取数据列表
        private IList<Student> GetStudents()
        {
            return JsonConvert.DeserializeObject<IList<Student>>(Read(Server.MapPath("~/students.json")));

            #region old data
            //return new List<Student>
            //{
            //    new Student
            //    {
            //        Name="张三",
            //        CreateTime=DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
            //        ID=1
            //    },new Student
            //    {
            //       Name="李四",
            //        CreateTime=DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
            //        ID=2
            //    },new Student
            //    {
            //        Name="王五",
            //        CreateTime=DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
            //        ID=3
            //    },new Student
            //    {
            //        Name="赵六",
            //        CreateTime=DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
            //        ID=4
            //    },new Student
            //    {
            //        Name="张小花",
            //        CreateTime=DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
            //        ID=5
            //    },new Student
            //    {
            //        Name="Beginner",
            //        CreateTime=DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
            //        ID=6
            //    }
            //};
            #endregion
        }
        //写入信息
        private void WriteStudents(string str)
        {
            Write(Server.MapPath("~/students.json"), str);
        }
        //读取文件
        private string Read(string path)
        {
            StreamReader sr = new StreamReader(path, Encoding.UTF8);
            var sb = new StringBuilder();
            String line;
            while ((line = sr.ReadLine()) != null)
            {
                sb.Append(line.ToString());
            }
            sr.Close();
            sr.Dispose();
            return sb.ToString();
        }
        //写入文件
        private void Write(string path, string str)
        {
            FileStream fs = new FileStream(path, FileMode.Create);
            StreamWriter sw = new StreamWriter(fs, Encoding.UTF8);
            //开始写入
            sw.Write(str);
            //清空缓冲区
            sw.Flush();
            //关闭流
            sw.Close();
            fs.Close();
        }
        #endregion
    }
    //student entity
    public class Student
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string CreateTime { get; set; }
    }

    //navbar entity
    public class Navbar
    {
        public string title { get; set; }
        public string icon { get; set; }
        public bool spread { get; set; } = false;
        public string href { get; set; }
        public IList<Navbar> children { get; set; }
    }
}